import CtlGridEditor from './CtlGridEditor'
import webix from 'webix'
import { YvEventDispatchArgs } from './YvanEvent'
import { CtlNumber } from './form/input/CtlNumber'

export default class CtlGridEditorNumber extends CtlGridEditor {
  isPinned: any
  $el: any
  $input: any
  leaveReason: any
  _id: any
  _editor: any

  init(params: any) {
    super.init(params)

    if (params.node.rowPinned) {
      this.isPinned = true
    }

    this._id = 'grid_editor_text' + webix.uid()
    this.$el = $(`<div id="${this._id}"></div>`)[0]
    this.$el.addEventListener('keydown', this._onKeyDown.bind(this))
  }

  _onKeyDown(e: any) {
    if (e.keyCode === 37 || e.keyCode === 39) {
      e.stopPropagation()
    }
    if (e.keyCode === 13) {
      this._editor._hideTootip()
    }
  }

  destroy() {
    super.destroy()
    this.$el.removeEventListener('keydown', this._onKeyDown.bind(this))
  }

  getGui() {
    return this.$el
  }

  _editValueOnInput(sender: any, event: any) {
    this.value = (event.target as any).value
    YvEventDispatchArgs(this.onChange, this, [this.value, this.data], this.vue._webix.$scope)
    this.vue._transactionUpdateRow(this.vue._gridData)
  }

  afterGuiAttached() {
    super.afterGuiAttached()
    const vjson = {
      ...this.editParams,
      view: this.type,
      value: this.value,
    }
    _.merge(vjson, {
      onInput: this._editValueOnInput.bind(this)
    })
    this._editor = CtlNumber.create(this.vue._module, vjson)
    webix.ui(vjson, this.$el)
    this._editor.focus()
  }

  getValue() {
    return this.value
  }

  focusIn() {
    super.focusIn()
  }

  focusOut() {
    super.focusOut()
  }
}
